package com.achobeta.recruitment.controller.manager;

import com.achobeta.recruitment.common.AppResult;
import com.achobeta.recruitment.common.ResultCode;
import com.achobeta.recruitment.model.Manager;
import com.achobeta.recruitment.service.manager.ManagerService;
import com.achobeta.recruitment.utils.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-31
 * Time: 13:55
 */
@Slf4j
@RestController
@RequestMapping("/manager")
@Api(tags = "管理员相关")
public class ManagerController {

    @Autowired
    private ManagerService managerService;



    /**
     * 登录验证
     * @param managerName 管理员名
     * @param password 密码
     * @return
     */
    @ApiOperation(value = "管理员登录", notes = "无data")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("管理员名") @RequestParam("managerName") @NonNull String managerName,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 1. 调用service的登录验证逻辑
        Manager manager = managerService.login(managerName, password);
        // 2. 如果user非空，设置到session里，同时框架帮我们返回setCookie
        if(manager != null) {
            SessionUtils.setManager(request, manager);
            return AppResult.success();
        }else {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
    }

    @GetMapping("/check")
    @ApiOperation(value = "管理员登录检测", notes = "当前管理员登录信息（如果登录了的话）")
    public AppResult<Manager> checkLogin(HttpServletRequest request) {
        // 这个接口应该只被管理员拦截器拦截，没被拦截器拦截则代表已登录，那么就直接返回manager
        return AppResult.success(SessionUtils.getManager(request));
    }

    @GetMapping("/logout")
    @ApiOperation(value = "管理员退出登录", notes = "data为空")
    public AppResult logout(HttpServletRequest request) {
        // 使session失效
        SessionUtils.remove(request);
        return AppResult.success();
    }
}
